package cn.ratel.db;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

class ModelBuilder {
	static <M extends Model> List<M> build(ResultSet rs, Class<? extends Model> clazz) {
		List<M> result = new ArrayList<>();
		try {
			ResultSetMetaData rsmd = rs.getMetaData();
			int columnCount = rsmd.getColumnCount();
			while (rs.next()) {
				Model<?> ar = clazz.newInstance();
				Map<String, Object> attrs = ar.attrs();
				for (int i = 1; i <= columnCount; i++) {
					String columnLabel = rsmd.getColumnLabel(i);
					Object columnValue = rs.getObject(i);
					if (columnValue != null && columnValue instanceof java.util.Date) {
						Date date = (Date) columnValue;
						columnValue = date.getTime();
					}
					attrs.put(columnLabel, columnValue);
				}
				result.add((M) ar);
			}
		} catch (SQLException | IllegalAccessException | InstantiationException e) {
			throw new RuntimeException("build Model error : ", e);
		}
		return result.isEmpty() ? null : result;
	}

}
